package require http
package require json

namespace eval planet {
	variable jsonAPI {http://nfk.pro2d.ru/api.php?action=gsl}
	variable httpException
	variable fplanet
	variable lastY
	variable metrics
	
	array set metrics { s,x 40 m,x 210 t,x 320 l,x 380 }
	
	font create font/planet/header -size 12 -weight "bold" -family "Tahoma"
	font create font/planet/body -size 10 -weight "bold" -family "Tahoma"
	
	proc getJson {} {
		variable jsonAPI
		variable httpException
		
		set httpException [catch {[set token [::http::geturl $jsonAPI \
				-command [namespace current]::getJsonClb]]}]
		
		# ::http::wait $token
	}
	
	proc getJsonClb {token} {
		variable fplanet
		
		set data [::http::data $token]
		set fplanet [::json::json2dict $data]
		
		updateServerList
		
		::http::cleanup $token
	}
	
	proc createPlanet {} {
		variable lastY
		variable metrics
		
		set p $::ui::Frames(content,planet)
		
		canvas $p.serverlist -background black -borderwidth 0 -highlightthickness 0
		pack $p.serverlist -fill both
		
		set lastY 20
		
		set opt {-fill white -anchor nw -font font/planet/header}
		$p.serverlist create text $metrics(s,x) $lastY -text "Server" {*}$opt
		$p.serverlist create text $metrics(m,x) $lastY -text "Map" {*}$opt
		$p.serverlist create text $metrics(t,x) $lastY -text "Type" {*}$opt
		$p.serverlist create text $metrics(l,x) $lastY -text "Load" {*}$opt
		
		incr lastY [expr {[font metrics font/planet/header -linespace] + 10}]
	}
	
	proc addLine {server map type load} {
		variable lastY
		variable metrics
		
		set p $::ui::Frames(content,planet)
		set opt {-fill white -anchor nw -font font/planet/body}
		
		$p.serverlist create text $metrics(s,x) $lastY -text $server {*}$opt
		$p.serverlist create text $metrics(m,x) $lastY -text $map {*}$opt
		$p.serverlist create text $metrics(t,x) $lastY -text $type {*}$opt
		$p.serverlist create text $metrics(l,x) $lastY -text $load {*}$opt

		incr lastY [font metrics font/planet/header -linespace]
	}
	
	proc updateServerList {} {
		variable fplanet
		
		foreach element $fplanet {
		
			addLine [dict get $element "name"] [dict get $element "map"] \
				[dict get $element "gametype"] [dict get $element "load"]
			# [dict get $element "ip"]
			
			set players [dict get $element "players"]
			if {$players eq  "null"} continue
			
			foreach player $players {
				# [dict get $player "name"] [dict get $player "country"] [dict get $player "model"][dict get $player "points"] [dict get $player "place"]
			}
		}
	}
	
	::hook::add finload [namespace current]::createPlanet
}
